import axios from 'axios';
import store from '@/store';

const API_URL = 'http://localhost:8080/library'; // 后端API地址

class ReaderService {
    // 获取所有读者
    getAllReaders() {
        return axios.get(`${API_URL}/readers?action=list`, {
            headers: this.getAuthHeader()
        }).then(response => response.data);
    }

    // 根据ID获取读者
    getReaderById(id) {
        return axios.get(`${API_URL}/readers?action=get&id=${id}`, {
            headers: this.getAuthHeader()
        }).then(response => response.data);
    }

    // 添加读者
    addReader(reader) {
        return axios.post(`${API_URL}/readers?action=add`, reader, {
            headers: this.getAuthHeader()
        }).then(response => response.data);
    }

    // 更新读者
    updateReader(reader) {
        return axios.post(`${API_URL}/readers?action=update`, reader, {
            headers: this.getAuthHeader()
        }).then(response => response.data);
    }

    // 删除读者
    deleteReader(id) {
        return axios.delete(`${API_URL}/readers?id=${id}`, {
            headers: this.getAuthHeader()
        }).then(response => response.data);
    }

    // 搜索读者
    searchReaders(keyword) {
        return axios.get(`${API_URL}/readers?action=search&keyword=${keyword}`, {
            headers: this.getAuthHeader()
        }).then(response => response.data);
    }

    // 获取认证头
    getAuthHeader() {
        const token = store.state.auth.token;
        if (token) {
            return { 'Authorization': 'Bearer ' + token };
        } else {
            return {};
        }
    }

    // 模拟数据方法 - 在实际连接API后可移除
    static mockData() {
        return [
            {id: 1, reader_id: 'R2023001', name: '张三', gender: '男', phone: '13800138000', email: 'zhangsan@example.com', register_date: '2023-01-15'},
            {id: 2, reader_id: 'R2023002', name: '李四', gender: '女', phone: '13900139000', email: 'lisi@example.com', register_date: '2023-02-20'},
            {id: 3, reader_id: 'R2023003', name: '王五', gender: '男', phone: '13700137000', email: 'wangwu@example.com', register_date: '2023-03-10'},
            {id: 4, reader_id: 'R2023004', name: '赵六', gender: '女', phone: '13600136000', email: 'zhaoliu@example.com', register_date: '2023-04-05'},
            {id: 5, reader_id: 'R2023005', name: '钱七', gender: '男', phone: '13500135000', email: 'qianqi@example.com', register_date: '2023-05-12'}
        ];
    }
}

// 导出单例实例
export default new ReaderService();